package com.monitor.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * copy.
 *
 * @author Li Zhiyuan
 * @since 2020/9/12
 */
@Data
public class PoJoUtil implements Serializable {
    private static final long serialVersionUID = 1L;

    private PoJoUtil() {
    }

    public static <S> S transToPoJo(Object o, Class<S> sClass) {
        if (o == null) {
            return ReflectUtil.newInstance(sClass);
        }
        S s = ReflectUtil.newInstance(sClass);
        BeanUtil.copyProperties(o, s);
        return s;
    }

    public static <S> List<S> transToPoJo(List list, Class<S> sClass) {
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<S> resultList = new ArrayList<>();
        list.forEach(l -> {
            S s = ReflectUtil.newInstance(sClass);
            BeanUtil.copyProperties(l, s);
            resultList.add(s);
        });
        return resultList;
    }

    /**
     * 转换类型
     */
    public static <T> List<T> PageUtil(IPage page, Class<T> tClass) {
        //将page的对象转换成tClass类型
        if (tClass == null) {
            return page.getRecords();
        } else {
            List records = page.getRecords();
            List<T> list = new ArrayList<>();
            for (Object record : records) {
                T o = ReflectUtil.newInstance(tClass);
                BeanUtil.copyProperties(record, o);
                list.add(o);
            }
            return list;
        }

    }

    /**
     * 返回总页码
     */
    public static Long Pages(Long total, Integer size) {
        if (total < size) {
            return 1L;
        } else {
            return (total % size == 0) ? (total / size) : (total / size) + 1;
        }
    }
}
